package com.bnz.service.impl;

import com.bnz.entity.Classes;
import com.bnz.entity.PageResult;
import com.bnz.entity.Student;
import com.bnz.mapper.ClassesMapper;
import com.bnz.mapper.StudentMapper;
import com.bnz.service.ClassesService;
import com.bnz.service.StudentService;
import com.bnz.vo.StudentVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private ClassesMapper classesMapper;

    //引入StudentMapper
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public List<Student> findAll() {
        return studentMapper.selectAll();
    }

    @Override
    public PageResult<String> findByPage(int page, int pageSize) {
        PageHelper.startPage(page,pageSize);

        Example example=new Example(Student.class);

        List<Student> students=studentMapper.selectByExample(example);

        for (Student student : students) {
            Classes classes= classesMapper.selectByPrimaryKey(student.getCid());
            student.setCname(classes.getCname());
        }

        Page<Student> studentPage= (Page<Student>) students;

        return new PageResult(studentPage.getTotal(),studentPage.getResult());

    }

    @Override
    public PageResult<String> search(int page, int pageSize, StudentVo vo) {
    PageHelper.startPage(page,pageSize);

    Example example=new Example(Student.class);

    Example.Criteria excr=example.createCriteria();

        if(vo != null){
            if(StringUtils.isNotBlank(vo.getSname())){
                excr.andLike("sname","%" + vo.getSname() + "%");
            }
            if(StringUtils.isNotBlank(vo.getAddr())){
                excr.andLike("addr","%" + vo.getAddr() + "%");
            }
            if(vo.getCid() != null && vo.getCid() != 0){
                excr.andEqualTo("cid",vo.getCid());
            }
        }


        List<Student> students=studentMapper.selectByExample(example);

        for (Student student : students) {
            Classes classes=classesMapper.selectByPrimaryKey(student.getCid());
            student.setCname(classes.getCname());
        }

        Page<Student> studentPage= (Page<Student>) students;

        return new PageResult(studentPage.getTotal(),studentPage.getResult());


    }

    @Override
    public void add(Student student) {
        studentMapper.insert(student);
    }

    @Override
    public void update(Student student) {
        studentMapper.updateByPrimaryKey(student);
    }

    @Override
    public void delete(Integer[] sids) {

        for (Integer sid : sids) {
            studentMapper.deleteByPrimaryKey(sid);
        }
    }


}
